# -*- coding: utf-8 -*-
class CommentsController < ApplicationController

  # config/routes.rb: map.resources :posts, :has_many => :comments
  # params[:post_id] は Post の id
  # params[:id] は Comment の id

  before_filter :find_post

  def index
    @comments = @post.comments
  end

  def show
    @comment = @post.comments.find params[:id]
  end

  def new
    @comment = @post.comments.build
  end

  def create
    @comment = @post.comments.build params[:comment]
    if @comment.save
      # insert 成功
      redirect_to post_comment_url(@post, @comment)
    else
      # insert 失敗
      render :action => :new
    end
  end

  def edit
    @comment = @post.comments.find params[:id]
  end

  def update
    @comment = Comment.find params[:id]
    if @comment.update_attributes params[:comment]
      # update 成功
      redirect_to post_comment_url(@post, @comment)
    else
      # update 失敗
      render :action => :edit
    end
  end

  def destroy
    @comment = Comment.find params[:id]
    @comment.destroy
    respond_to do |format|
      format.html { redirect_to post_comments_path(@post) }
      format.xml  { head :ok }
    end
  end

  private
  def find_post
    @post = Post.find params[:post_id]
  end
end
